package com.sun.dubbo.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;

import com.sun.dubbo.service.DubboService;
import com.sun.dubbo.service.RedisClusterService;
import com.sun.pojo.Menu;
import com.sun.pojo.MenuCustom;
import com.sun.webmanage.mapper.MenuMapper;

//DubboServiceImpl已经通过xml方式交由spring管理  不在需要@Service标签
public class DubboServiceImpl implements DubboService{

	@Resource
	private MenuMapper menuMapper;
	@Resource
	private RedisClusterService redisClusterService;
	
	@Value("${menu.list.all.key}")
	private String menu_list_all_key;
	
	@Override
	public List<MenuCustom> listMenu() {
		/*if(redisClusterService.exists(menu_list_all_key)){
			String listJson = redisClusterService.getKey(menu_list_all_key);
			List<MenuCustom> listdata = JsonUtils.jsonToList(listJson, MenuCustom.class);
			return listdata;
		}else{
			List<MenuCustom> listMenuTree = listMenuTree(menuMapper.listRootMenu());
			String objectToJson = JsonUtils.objectToJson(listMenuTree);
			redisClusterService.setKey(menu_list_all_key, objectToJson);
			return listMenuTree;
		}*/
		List<MenuCustom> listMenuTree = listMenuTree(menuMapper.listRootMenu());
		return listMenuTree;
	}
	
	/**
	 * 递归检索root下所有子类树
	 * @param rootlist
	 * @return
	 */
	private List<MenuCustom> listMenuTree(List<MenuCustom> rootlist){
		for(MenuCustom menu:rootlist){
			menu.setSpread(true);
			 List<MenuCustom> listChild = menuMapper.listChildMenuByPid(menu.getId());
			 if(listChild!=null && !listChild.isEmpty()){
				 menu.setChildren(listChild);
				 this.listMenuTree(listChild);//装载子类下的子类
			 }
		 }
			return rootlist;
	}

	@Override
	public boolean updateMenu(Menu menu) {
		 if(menuMapper.updateMenu(menu)>0){
			 return true;
		 }
		 
		 return false;
	}

	@Override
	public Menu loadMenu(Integer id) {
		return menuMapper.loadMenu(id);
	}

	@Override
	public Integer saveMenu(Menu menu) {
		if(menuMapper.saveMenu(menu)>0){
			return menu.getId();
		}
		return null;
	}

	@Override
	public boolean delMenu(Integer id) {
		if(menuMapper.delMenu(id)>0){
			return true;
		}
		return false;
	}

}
